# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Node, NodeList, Template, Context, resolve_variable
from django.template import get_library, Library, InvalidTemplateLibrary, TemplateSyntaxError
from django.template.loader import get_template
from django.db.models import get_model
from apps.core.models.element import Element

register = Library()

class ContentNode(Node):
    def __init__(self, section, templates, limit, offset):
        self.__default_structure = "core.Section" 
        self.__section = section
        self.__templates = templates 
        self.__limit = limit
        self.__offset = offset
        
    def render(self, context): 
        nodes = NodeList()
        section= None
        if not "current" in self.__section:
            try:
                section = get_model(*self.__default_structure.split("."))
                model = section.objects.get(name=self.__section)
            except:
                raise TemplateSyntaxError, "Il content specificato non e' valido"
        else:
            model = context['section']
        
        if context.get('selected_articles'):
            related_content = model.article_set.filter(name__iexact=context['selected_articles']['name'])
        else:    
            #related_content = model.article_set.all().exclude(status__exact=1)
            related_content = Element.objects.filter(section__exact=model.id).exclude(status__exact=1)
            
        
        if not self.__limit:
            self.__limit = related_content.count()

        #related_content = gettattr(model, "article_set")
        if (self.__limit == 1) and len(self.__templates) > 1:
            tpl = get_template(self.__templates[1])
        else:
            tpl = get_template(self.__templates[0])
        
        for content in related_content[self.__offset:self.__limit]:
            '''
            for k,v in content.__dict__.items():
                print "%s = %s" % (k,v)
                context['content']['']
            '''
            context['content'] = content
            for node in tpl:
                nodes.append(node.render(context))
        return nodes.render(context)

def get_content(parser, token):
    """
        example tags:
        {% get_content using "templatedir/template" limit 10 offset 5 %}
        {% get_content from blog using "template" limit 10 %}
    """
    params = token.contents.split()
    section = "current"
    custom_templates = []
    limit = None 
    offset = 0
    if (len(params)%2):
         
        if "using" in params:
            custom_templates.append("%s.html" % params[params.index("using")+1][1:-1])
            try:
                if "or" in params[params.index("using")+2]:
                    custom_templates.append("%s.html" % params[params.index("or")+1][1:-1])
            except IndexError:
                pass
                
        if "limit" in params:
            try: limit = int(params[(params.index("limit")+1)])
            except:
                raise TemplateSyntaxError, """
                    il valore specificato per 'limit' deve essere un intero"""
                    
        if "offset" in params:
            try: offset = int(params[(params.index("offset")+1)])
            except:
                raise TemplateSyntaxError, """
                    il valore specificato per 'offset' deve essere un intero"""
                    
        if "from" in params:
            section = params[params.index("from")+1][1:-1]                 
    else:
        raise TemplateSyntaxError, "il numero di argomenti in %r non e' corretto" % params[0]
    return ContentNode(section, custom_templates, limit, offset)
get_content = register.tag(get_content)
